package com.huilian.cloud.module.system.service.usergroup;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.huilian.cloud.module.system.controller.admin.usergroup.vo.*;
import com.huilian.cloud.module.system.dal.dataobject.usergroup.UserGroupDO;
import com.huilian.cloud.framework.common.pojo.PageResult;
import com.huilian.cloud.framework.common.pojo.PageParam;
import com.huilian.cloud.framework.common.util.object.BeanUtils;

import com.huilian.cloud.module.system.dal.mysql.usergroup.UserGroupMapper;

import static com.huilian.cloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.huilian.cloud.module.system.enums.ErrorCodeConstants.*;

/**
 * 用户与用户组关联 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class UserGroupServiceImpl implements UserGroupService {

    @Resource
    private UserGroupMapper userGroupMapper;

    @Override
    public Integer createUserGroup(UserGroupSaveReqVO createReqVO) {
        // 插入
        UserGroupDO userGroup = BeanUtils.toBean(createReqVO, UserGroupDO.class);
        userGroupMapper.insert(userGroup);
        // 返回
        return userGroup.getGroupId();
    }

    @Override
    public void updateUserGroup(UserGroupSaveReqVO updateReqVO) {
        // 校验存在
        validateUserGroupExists(updateReqVO.getGroupId());
        // 更新
        UserGroupDO updateObj = BeanUtils.toBean(updateReqVO, UserGroupDO.class);
        userGroupMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserGroup(Integer id) {
        // 校验存在
        validateUserGroupExists(id);
        // 删除
        userGroupMapper.deleteById(id);
    }

    private void validateUserGroupExists(Integer id) {
        if (userGroupMapper.selectById(id) == null) {
            throw exception(USER_GROUP_NOT_EXISTS);
        }
    }

    @Override
    public UserGroupDO getUserGroup(Integer id) {
        return userGroupMapper.selectById(id);
    }

    @Override
    public PageResult<UserGroupDO> getUserGroupPage(UserGroupPageReqVO pageReqVO) {
        return userGroupMapper.selectPage(pageReqVO);
    }

}